package com.base.common.advice;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.enums.AppType;
import com.base.common.enums.SmsCategories;
import com.base.common.enums.SmsType;
import com.base.common.enums.TicketCategories;
import com.base.common.enums.TicketReportCategories;
import com.base.common.enums.TicketReportStatus;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.CompoundsMapper;
import com.base.common.persistent.dao.EmployeeCompoundsMapper;
import com.base.common.persistent.dao.EmployeeMapper;
import com.base.common.persistent.dao.SmsMapper;
import com.base.common.persistent.dao.SmsReportMapper;
import com.base.common.persistent.dao.TerminalMapper;
import com.base.common.persistent.dao.TicketMapper;
import com.base.common.persistent.dao.TicketReportMapper;
import com.base.common.persistent.dao.VillageConfigMapper;
import com.base.common.persistent.model.Compounds;
import com.base.common.persistent.model.Employee;
import com.base.common.persistent.model.Sms;
import com.base.common.persistent.model.Terminal;
import com.base.common.persistent.model.Ticket;
import com.base.common.persistent.model.TicketReport;
import com.base.common.persistent.model.User;
import com.base.common.utils.EasyUtil;
import com.base.common.utils.PushUtils;
import com.opensymphony.xwork2.ActionContext;

/**
 * 工单提交方法的aop切面
 * 
 * @author Kevin Colin
 * 
 */
@Component
@Aspect
public class AspectAdvice {

	@Resource
	private EasyUtil easyUtil;

	@Resource
	private TicketMapper ticketMapper;

	@Resource
	private EmployeeMapper employeeMapper;

	@Resource
	private TerminalMapper terminalMapper;

	@Resource
	private SmsReportMapper smsReportMapper;

	@Resource
	private SmsMapper smsMapper;

	@Resource
	private CompoundsMapper compoundsMapper;

	@Resource
	private EmployeeCompoundsMapper employeeCompoundsMapper;

	@Resource
	private TicketReportMapper ticketReportMapper;
	
	@Resource
	private VillageConfigMapper villageConfigMapper;

	@Pointcut("execution(* com.cjy.userReport.service.*.impl.*.sub*(..))")
	public void subTicketMethod() {
	}

	@Pointcut("execution(* com.ygj.employeeReport.service.*.impl.*.sub*(..))")
	public void subYGJTicketMethod() {
	}

	@Transactional
	@AfterReturning(value = "subTicketMethod()", returning = "result")
	public void doAfterSub(JoinPoint jp, String result) {
		try {
			System.out.println("进入aop");

			// 获取报修物业id
			Ticket ticket = (Ticket) jp.getArgs()[0];
			int userId = ticket.getUser().getId();

			// 获取session, 查找物业信息
			Map<String, Object> session = ActionContext.getContext()
					.getSession();
			List<User> users = (List<User>) session.get("users");
			User user = null;
			for (int i = 0; i < users.size(); i++) {
				if (users.get(i).getId() == userId) {
					user = users.get(i);
					break;
				}
			}

			// 给业主app发送通知
			List<Terminal> terminalList = terminalMapper
					.queryTerminalByPhoneRegisted(ticket.getSubUserPhone(),
							AppType.CJY.getValue());
			String cappleClientId = null;
			String candroidClientId = null;
			String mess = null;
			if (terminalList.size() > 0) {
				mess = "尊敬的业主您好，您的工单已受理，工单号为" + result;
				if (terminalList.get(0).getAppleClientId() != null
						&& !"".equals(terminalList.get(0).getAppleClientId()
								.trim())) {
					cappleClientId = terminalList.get(0).getAppleClientId();
					// sendSms(mess, phone, clientId, appType, type, smsId,
					// receiveTerminalId, senderTerminalId);
					sendSms(mess, ticket.getSubUserPhone(), cappleClientId,
							AppType.CJY.getValue(), SmsType.MAIN.getValue(), 0,
							terminalList.get(0).getId(), 0);
				}

				if (terminalList.get(0).getAndroidClientId() != null
						&& !"".equals(terminalList.get(0).getAndroidClientId()
								.trim())) {
					candroidClientId = terminalList.get(0).getAndroidClientId();
					sendSms(mess, ticket.getSubUserPhone(), candroidClientId,
							AppType.CJY.getValue(), SmsType.MAIN.getValue(), 0,
							terminalList.get(0).getId(), 0);
				}
			}

			// 查询员工ID
			Employee employee = employeeMapper.queryEmployeeByPhone(
					user.getCompounds().getManagerPhone()).get(0);

			if("1".equals(villageConfigMapper.getSendSmsFlag(user.getCompounds().getId()).trim())){
				// 给项目经理发送短信
				easyUtil.sendSms("有新的工单需要您处理，工单号为" + result, user.getCompounds()
						.getManagerPhone());
				
			}

			// 给员工app发送通知
			List<Terminal> terminals = terminalMapper
					.queryTerminalById(employee.getTerminal().getId());
			String appleClientId = null;
			String androidClientId = null;
			if (terminals.size() > 0) {
				mess = "有新的工单需要您处理，工单号为" + result;
				if (terminals.get(0).getAppleClientId() != null) {
					appleClientId = terminals.get(0).getAppleClientId();
					// sendSms(mess, phone, clientId, appType, type, smsId,
					// receiveTerminalId, senderTerminalId);
					sendSms(mess, user.getCompounds().getManagerPhone(),
							appleClientId, AppType.YGJ.getValue(),
							SmsType.MAIN.getValue(), 0, terminalList.get(0)
									.getId(), 0);
				}

				if (terminals.get(0).getAndroidClientId() != null) {
					androidClientId = terminals.get(0).getAndroidClientId();
					sendSms(mess, user.getCompounds().getManagerPhone(),
							androidClientId, AppType.YGJ.getValue(),
							SmsType.MAIN.getValue(), 0, terminalList.get(0)
									.getId(), 0);
				}
			}

			// 查询工单ID
			Ticket sTicket = ticketMapper.queryTicketByCode(result);

			// 插入工单记录
			addReport(sTicket, employee,
					TicketReportStatus.UNTREATED.getValue(),
					TicketReportCategories.DISPATCH.getValue());

			// 判断是否是临时工单，如果是临时工单转换成报修工单
			if (ticket.getCategories() == TicketCategories.TEMPORARY.getValue()) {
				ticketMapper.updateCategoriesById(sTicket.getId(),
						TicketCategories.REPAIR.getValue());
				List<Ticket> tickets = ticketMapper
						.queryLastCodeByCategories(TicketCategories.TEMPORARY
								.getValue());
				String code = "";
				DecimalFormat df = new DecimalFormat("000000");
				if (tickets.size() != 0) {
					String lastedCode = tickets.get(0).getCode();
					code = df.format(Integer.parseInt(lastedCode.substring(1)
							.trim()) + 1);
				}
				code = TicketCategories.REPAIR.getName() + code;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * @param mess
	 * @param phone
	 * @param clientId
	 * @param appType
	 * @param type
	 * @param smsId
	 * @param senderTerminalId
	 */
	public void sendSms(String mess, String phone, String clientId,
			int appType, int type, int smsId, int receiveTerminalId,
			int senderTerminalId) {
		Sms sms = easyUtil.addSms(SmsCategories.STSTEMNOTIFIER.getValue(),
				SmsCategories.STSTEMNOTIFIER.getName(), mess, phone, type,
				smsId, receiveTerminalId, senderTerminalId);

		try {
			System.out.println(PushUtils.pushtoSingle(clientId,
					JsonUtil.dto2String(sms), appType));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Transactional
	@AfterReturning(value = "subYGJTicketMethod()", returning = "result")
	public void doAfterEmployeeSub(JoinPoint jp, String result) {
		System.out.println("进入aop");

		// 获取session, 查找物业信息
		// Map<String, Object> session =
		// ActionContext.getContext().getSession();
		// List<Employee> employees = (List<Employee>) session.get("users");
		// 获取报修物业信息
		Ticket ticket = (Ticket) jp.getArgs()[0];

		Compounds compounds = compoundsMapper.queryCompoundsById(
				ticket.getCompounds().getId()).get(0);

        boolean disflag = (boolean) jp.getArgs()[1];

        // 获取session, 查找物业信息
        Map<String, Object> session = ActionContext.getContext()
                .getSession();


        // 查询工单ID
		System.out.println("-----------------------------------\n" + result);
		
		Ticket sTicket = ticketMapper.queryTicketByCode(result);


		// 查询员工ID
		Employee employee;
        if (disflag == true) {
            employee = ((List<Employee>)session.get("users")).get(0);
        } else {
        	employee = employeeMapper.queryEmployeeByPhone(
                compounds.getManagerPhone()).get(0);
		}

        // 插入工单记录
		addReport(sTicket, employee, TicketReportStatus.UNTREATED.getValue(),
				TicketReportCategories.DISPATCH.getValue());

		// 给员工app发送通知
		List<Terminal> terminals = terminalMapper.queryTerminalById(employee
				.getTerminal().getId());
		String appleClientId = null;
		String androidClientId = null;
		/*
		 * if (terminals.size() > 0) { if (terminals.get(0).getAppleClientId()
		 * != null) { appleClientId = terminals.get(0).getAppleClientId(); Sms
		 * sms = easyUtil.addSms(SmsCategories.STSTEMNOTIFIER .getValue(),
		 * SmsCategories.STSTEMNOTIFIER.getName(), "有新的订单需要您处理，订单号为" + result,
		 * employees.get(0) .getCompounds().getManagerPhone(), employee.getId(),
		 * 0); try { System.out.println(PushUtils.pushtoSingle(appleClientId,
		 * JsonUtil.dto2String(sms), AppType.YGJ.getValue())); } catch
		 * (Exception e) { e.printStackTrace(); } }
		 * 
		 * if (terminals.get(0).getAndroidClientId() != null) {
		 * 
		 * androidClientId = terminals.get(0).getAndroidClientId(); Sms sms =
		 * easyUtil.addSms(SmsCategories.STSTEMNOTIFIER .getValue(),
		 * SmsCategories.STSTEMNOTIFIER.getName(), "有新的订单需要您处理，订单号为" + result,
		 * employees.get(0) .getCompounds().getManagerPhone(), employee.getId(),
		 * 0); try { System.out.println(PushUtils.pushtoSingle(androidClientId,
		 * JsonUtil.dto2String(sms), AppType.YGJ.getValue())); } catch
		 * (Exception e) { e.printStackTrace(); }
		 * 
		 * } }
		 */
		String mess = null;
		if (terminals.size() > 0) {
			mess = "有新的工单需要您处理，工单号为" + result;
			// sendSms(mess, phone, clientId, appType, type, smsId,
			// receiveTerminalId, senderTerminalId);
			// int employeeCompounds =
			// employeeCompoundsMapper.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(employee.getId(),
			// compounds.getId());
			if (terminals.get(0).getAppleClientId() != null) {
				appleClientId = terminals.get(0).getAppleClientId();
				sendSms(mess, compounds.getManagerPhone(), appleClientId,
						AppType.YGJ.getValue(), SmsType.MAIN.getValue(), 0,
						terminals.get(0).getId(), 0);
			}

			if (terminals.get(0).getAndroidClientId() != null) {
				androidClientId = terminals.get(0).getAndroidClientId();
				sendSms(mess, compounds.getManagerPhone(), androidClientId,
						AppType.YGJ.getValue(), SmsType.MAIN.getValue(), 0,
						terminals.get(0).getId(), 0);
				// sendSms(mess, compounds.getManagerPhone(), 0,
				// employee.getId(), androidClientId, AppType.YGJ.getValue());
			}
			
			// 判断当前小区下是否发送通知短信
			if("1".equals(villageConfigMapper.getSendSmsFlag(compounds.getId()).trim())){
				easyUtil.sendSms(mess, compounds.getManagerPhone());
			}
		}
	}

	/**
	 * @param sTicket
	 * @param employee
	 */
	public void addReport(Ticket sTicket, Employee employee, int reportStatus,
			int reportCategories) {
		TicketReport ticketReport = new TicketReport();
		ticketReport.setStartTime(new Date());
		ticketReport.setEmployee(new Employee().setId(employee.getId()));
		ticketReport.setTicket(new Ticket().setId(sTicket.getId()));
		ticketReport.setCategories(reportCategories);
		ticketReport.setStatus(reportStatus);
		ticketReportMapper.addTicketReport(ticketReport);
	}
}
